package com.lhy.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.lhy.pojo.Files;
import com.lhy.service.EchartsService;
import com.lhy.service.FileService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/files")
public class FileController {
    @Resource
    private GridFsTemplate gridFsTemplate;

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Resource
    private FileService fileService;


    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename=file.getOriginalFilename();
        String type= FileUtil.extName(originalFilename);
        long size = file.getSize();
        //存到磁盘
        File uploadParentFile = new File(fileUploadPath);
        if(!uploadParentFile.exists()){
            uploadParentFile.mkdirs();
        }
        //定义一个文件唯一的标识码
        String uuid= IdUtil.fastSimpleUUID();
        String fileUuid= uuid + StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUuid);

        //获取到的文件存到磁盘目录
        file.transferTo(uploadFile);

        String url="http://localhost:8080/files/"+fileUuid;

        //下载链接
        return url;
    }

    //下载
    @GetMapping("/{fileUuid}")
    public void download(@PathVariable String fileUuid, HttpServletResponse response) throws IOException{
        File uploadFile = new File(fileUploadPath + fileUuid);  //上传的文件路径
        //设置输出流格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUuid,"UTF-8"));
        response.setContentType("application/octet-stream");

        //读文件字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }


}
